package com.itmumu.miniwechat.chat.websocket.netty;

import com.itmumu.miniwechat.chat.websocket.ChannelContextUtil;
import com.itmumu.miniwechat.common.constants.RedisKey;
import com.itmumu.miniwechat.common.utils.JsonUtils;
import com.itmumu.miniwechat.common.utils.RedisComponent;
import com.itmumu.miniwechat.common.utils.RedisUtils;
import com.itmumu.miniwechat.user.domain.dto.TokenUserInfoDto;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.Attribute;
import io.netty.util.AttributeKey;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
@ChannelHandler.Sharable
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Resource
    private RedisComponent redisComponent;

    @Resource
    private ChannelContextUtil channelContextUtils;


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("有新的连接加入。。。");
    }

    /**
     * 当通道不再活跃时（连接关闭）会调用此方法，我们可以在这里做一些清理工作
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        log.info("有连接已经断开。。。");
//        channelContextUtils.removeContext(ctx.channel());
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof WebSocketServerProtocolHandler.HandshakeComplete) {
            log.info("握手成功。。。");
            WebSocketServerProtocolHandler.HandshakeComplete complete = (WebSocketServerProtocolHandler.HandshakeComplete) evt;
            String url = complete.requestUri();

            String token = getToken(url);
            if (token == null) {
                ctx.channel().close();
                return;
            }

            TokenUserInfoDto userInfo = redisComponent.getTokenUserInfoDto(token);
            log.info("userinfo ===> {}", userInfo);
            if (Objects.isNull(userInfo)) {
                ctx.channel().close();
                return;
            }

            // 有用户加入
            channelContextUtils.addContext(userInfo.getUid(), ctx.channel());
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        Channel channel = ctx.channel();
        Attribute<Integer> attribute = channel.attr(AttributeKey.valueOf(channel.id().toString()));
        Integer uid = attribute.get();
        log.info("收到userid：{}消息，msg: {}", uid, msg.text());

        redisComponent.saveUserHeartBeat(uid);
    }

    private String getToken(String url) {
        if (StringUtils.isEmpty(url) || url.indexOf("?") == -1) {
            return null;
        }
        String[] queryParams = url.split("\\?");
        if (queryParams.length < 2) {
            return url;
        }
        String[] params = queryParams[1].split("=");
        if (params.length != 2) {
            return url;
        }
        return params[1];
    }
}
